﻿using Eyskens.AutoTaggerWeb.Helpers;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Taxonomy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Eyskens.AutoTaggerWeb.Controllers
{
    public class KeywordController : Controller
    {
        // GET: Keyword
        public ActionResult Index()
        {
            
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        // POST: EmptyWords/Create
        [HttpPost]
        public ActionResult Create(System.Web.Mvc.FormCollection collection)
        {
            
            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
                using (var ctx = spContext.CreateUserClientContextForSPHost())
                {
                    Guid g = AutoTaggingHelper.AddKeyWord(collection["k"], ctx);
                }
                return View("Index");

            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
                throw;
            }
        }

        public ActionResult Tag()
        {
            return View();
        }

        // POST: EmptyWords/Create
        [HttpPost]
        public ActionResult Tag(System.Web.Mvc.FormCollection collection)
        {

            try
            {
                LogHelper.Log("Tagging process started");
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
                using (var ctx = spContext.CreateUserClientContextForSPHost())
                {
                    StringBuilder vals = new StringBuilder();
                    Guid g = AutoTaggingHelper.AddKeyWord(collection["k"], ctx);
                    LogHelper.Log("tag id :" + g.ToString());
                    ListItem _item = ctx.Web.Lists.GetById(
                        new Guid(HttpContext.Request.QueryString["SPListId"])).GetItemById(
                        HttpContext.Request.QueryString["SPListItemId"]);
                    FieldCollection _fields = ctx.Web.Lists.GetById(
                        new Guid(HttpContext.Request.QueryString["SPListId"])).Fields;
                    ctx.Load(_item);
                    ctx.Load(_fields);
                    ctx.ExecuteQuery();
                    LogHelper.Log("after exec");
                    TaxonomyFieldValueCollection CurrentValue = _item["TaxKeyword"] as TaxonomyFieldValueCollection;
                    if(CurrentValue!=null && CurrentValue.Count>0)
                    {
                        foreach(TaxonomyFieldValue val in CurrentValue)
                        {
                            vals.AppendFormat("-1;#{0}|{1};", val.Label, val.TermGuid);
                        }
                    }
                    
                    vals.AppendFormat("-1;#{0}|{1};", collection["k"], g);
                    LogHelper.Log("values:" + vals.ToString());
                    TaxonomyField _field = ctx.CastTo<TaxonomyField>(_fields.GetByInternalNameOrTitle(
                        Constants.TaxFieldInternalName));
                    TaxonomyFieldValueCollection col = new TaxonomyFieldValueCollection(ctx, string.Empty, _field);
                    col.PopulateFromLabelGuidPairs(vals.ToString());
                    _field.SetFieldValueByValueCollection(_item, col);
                    _item.Update();
                    ctx.ExecuteQuery();
                }
                return View("Index");

            }
            catch (Exception ex)
            {
                LogHelper.Log(ex.Message + ex.StackTrace, LogSeverity.Error);
                throw;
            }
        }
    }
}